package org.csu.logistics.Controller;

import org.csu.logistics.Service.LogService;
import org.csu.logistics.Service.MailService;
import org.csu.logistics.common.CommonResponse;
import org.csu.logistics.entity.User;
import org.csu.logistics.entity.log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@CrossOrigin(origins = "http://47.100.72.98:80")
@RequestMapping("/Login/")
public class LoginController {
    @Autowired
    private LogService login_service;
    @Autowired
    private MailService mailService;

    @PostMapping("/login")
    @CrossOrigin(origins = "http://47.100.72.98:80")
    @ResponseBody
    public CommonResponse<log> login(@RequestBody Map<String,String> data){
        int userid = Integer.parseInt(data.get("userid"));
        String password = data.get("pwd");
        if(login_service.judgeIFLogin(userid, password, Integer.parseInt(data.get("aut")))) {
            return CommonResponse.createForSuccess();
        }
        return CommonResponse.createForError();
    }

    @PostMapping("/register")
    @CrossOrigin(origins = "http://47.100.72.98:80")
    @ResponseBody
    public CommonResponse<log> IntoUserSetting(@RequestBody Map<String,String> account)
    {
        String userid = account.get("userid");
        if(login_service.judgeUserid(userid)){
            User user = new User(Integer.parseInt(account.get("userid")),account.get("name"),Integer.parseInt(account.get("age")),
                    account.get("sex"),account.get("tel"),account.get("addr"),0);
            log log = new log(Integer.parseInt(account.get("userid")),account.get("pwd"),account.get("tel"),0);
            login_service.insert_account(user);
            login_service.insert_log(log);

            return CommonResponse.createForSuccessMessage("注册成功，请完成登录");
        }
        return CommonResponse.createForError("用户id重复");
    }
    @PostMapping("/updateByEmail")
    @CrossOrigin(origins = "http://47.100.72.98:80")
    @ResponseBody
    public CommonResponse<log> UpdateByEmail(@RequestBody Map<String,String> data){
        String email = data.get("email");
        String password = data.get("pwd");
        login_service.change_password(email, password);
        return CommonResponse.createForSuccess();
    }
}
